﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YmtAuth.Common.Extend;
using YmtAuth.Domain.Model.Safe;
using YmtAuth.Domain.Repository;
using YmtSystem.CrossCutting;

namespace YmtAuth.AppService.Safe
{
   /// <summary>
   /// 用户安全认证相关参数配置
   /// </summary>
    public class SafeVerifyConfiguration
    {
        private static readonly IAuthConfigurationRepository cfgRepo = LocalServiceLocator.GetService<IAuthConfigurationRepository>();        
        /// <summary>
        /// 登录安全验证配置
        /// </summary>
        public class LoginSafeCfg
        {
            private static IDictionary<string, string> loginSafeCfg = new Dictionary<string, string>();
            private static DateTime cacheStartTime = DateTime.Now;
            private const int timeOutminutes = 3;
            private const string appid = "LoginSafe";
            
                   

            public static IDictionary<string, string> GetLoinSafeConfiguration()
            {
                if (loginSafeCfg.Count > 0 && DateTime.Now <= cacheStartTime)
                {
                    return loginSafeCfg;
                }
                cacheStartTime = DateTime.Now.AddMinutes(timeOutminutes);
                var cfgList = cfgRepo.TryFind(appid);
                if (cfgList != null && cfgList.Any())
                {
                    YmatouLoggingService.Info("获取到DB登录安全配置，下次刷新数据时间 {0}", cacheStartTime);
                    loginSafeCfg = cfgList.ToDictionary(k => k.GetKey(), v => v.Value);
                }
                else
                {
                    loginSafeCfg = DefaultLoinSafeCfg();
                    YmatouLoggingService.Debug("未取到登录安全配置库配置使用默认配置，下次刷新数据时间 {0}", cacheStartTime);
                }
                return loginSafeCfg;
            }

            private static IDictionary<string, string> DefaultLoinSafeCfg()
            {
                loginSafeCfg = new Dictionary<string, string>();
                loginSafeCfg[SafeCfgKey.LoginSafe_Pc_Open] = "1";
                
                loginSafeCfg[SafeCfgKey.LoginSafe_Pc_GetUserIpArea] = "0";

                loginSafeCfg[SafeCfgKey.LoginSafe_PcLoginPas_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcLoginPas_ErrorAction] = "100";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcLoginPas_CheckSpec] = "10,6";

                loginSafeCfg[SafeCfgKey.LoginSafe_PcIp_ExistsCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcIp_NotExistsIdentityVerify] = "100";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcIp_AuthStatusCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcIp_AuthFailAction] = "100";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcIp_AuthSuccessAction] = "200";

                loginSafeCfg[SafeCfgKey.LoginSafe_PcBlacklist_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcBlacklist_BlacklistAction] = "400";

                loginSafeCfg[SafeCfgKey.LoginSafe_PcToken_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_PcToken_LastAuthDay] = "90";
               
                //////////////////////////////////////////////////////////
                loginSafeCfg[SafeCfgKey.LoginSafe_App_Open] = "1";

                loginSafeCfg[SafeCfgKey.LoginSafe_App_GetUserDevice] = "0";
                
                loginSafeCfg[SafeCfgKey.LoginSafe_AppLoginPas_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppLoginPas_ErrorAction] = "100";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppLoginPas_CheckSpec] = "10,6";

                loginSafeCfg[SafeCfgKey.LoginSafe_AppDevice_ExistsCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppDevice_NotExists] = "100";

                loginSafeCfg[SafeCfgKey.LoginSafe_AppDevice_StatusCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppDevice_AuthSuccessAction] = "200";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppDevice_AuthFailAction] = "100";

                loginSafeCfg[SafeCfgKey.LoginSafe_AppClientId_ExistsCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppClientIde_StatusCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppClientId_AuthSuccessAction] = "200";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppClientId_AuthFailAction] = "100";

                loginSafeCfg[SafeCfgKey.LoginSafe_AppBlacklist_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppBlacklist_BlacklistAction] = "400";

                loginSafeCfg[SafeCfgKey.LoginSafe_AppToken_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppToken_LastAuthDay] = "180";
                loginSafeCfg[SafeCfgKey.LoginSafe_Check_List] =
                    ConfigurationManager.AppSettings["LoginSafe_Check_List"] ?? "*";
                //2016.7.5
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIpUserToken_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIp_ExistsCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIp_AuthStatusCheck] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppPartial_Mode] = "0";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIp_AuthFailAction] = "100";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIp_AuthSuccessAction] = "200";
                //2016.7.13
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIpBlacklist_Check] = "1";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppIpBlacklist_BlacklistAction] = "400";
                //2016.7.14
                loginSafeCfg[SafeCfgKey.LoginSafe_PcUserFirstLogin_AutoAuthSuccess] = "0";
                loginSafeCfg[SafeCfgKey.LoginSafe_AppUserFirstLogin_AutoAuthSuccess] = "0";

                //2016.7.14
                loginSafeCfg[SafeCfgKey.LoginSafe_LoginIdLimit_CheckSpec] = "1,30";
                //2016.8.15
                loginSafeCfg[SafeCfgKey.KeyFormart(SafeCfgKey.LoginSafe_PcIp_ExistsCheck,"seller")] = "0";
                loginSafeCfg[SafeCfgKey.KeyFormart(SafeCfgKey.LoginSafe_PcToken_Check,"seller")] = "0";
                loginSafeCfg[SafeCfgKey.KeyFormart(SafeCfgKey.LoginSafe_PcToken_LastAuthDay, "seller")] = "90";
                return loginSafeCfg;
            }
        }
        /// <summary>
        /// 黑名单参数
        /// </summary>
        public class BlackListCfg
        {          
            private static IDictionary<string, string> ipBlacklistCfg = new Dictionary<string, string>();
            private static DateTime cacheStartTime = DateTime.Now;
            private const int timeOutminutes = 3;
            private const string blacklist_id = "blacklist_ip_0";

            public static IDictionary<string, string> GetIpBlacklistConfiguration()
            {
                bool iscahce;
                return GetIpBlacklistConfiguration(out iscahce);
            }

            public static IDictionary<string, string> GetIpBlacklistConfiguration(out bool isCache)
            {
                isCache = false;
                if (ipBlacklistCfg.Count > 0 && DateTime.Now <= cacheStartTime)
                {
                    isCache = true;
                    return ipBlacklistCfg;
                }
                cacheStartTime = DateTime.Now.AddMinutes(timeOutminutes);              
                var cfg = Action_Extend.ActionWatch(() => cfgRepo.TryFind("BlackList"), "[GetIpBlacklistConfiguration] Find MySQL Database");                
                if (cfg != null && cfg.Any())
                {
                    ipBlacklistCfg = cfg.ToDictionary(k => k.GetKey(), v => v.Value);
                    YmatouLoggingService.Info("获取到DBIP黑名单配置策略,缓存过期 {0}", cacheStartTime);
                    return ipBlacklistCfg;
                }              
                YmatouLoggingService.Debug("数据库没有配置IP黑名单策略，使用本地配置文件策略");
                ipBlacklistCfg = new Dictionary<string, string>();
                ipBlacklistCfg[IpBlackListKey("Open")] = ConfigurationManager.AppSettings["BlackIpRequestCheck"];
                ipBlacklistCfg[IpBlackListKey("RequestFailIpLockExpired")] = ConfigurationManager.AppSettings["RequestFailIpLockExpiredTime"];
                ipBlacklistCfg[IpBlackListKey("RequestSuccessIpLockExpired")] = ConfigurationManager.AppSettings["RequestSuccessIpLockExpiredTime"];
                ipBlacklistCfg[IpBlackListKey("LoginSuccessLimitMinutes")] = ConfigurationManager.AppSettings["IpLoginSuccessLimitMinutes"];
                ipBlacklistCfg[IpBlackListKey("LoginFailLimitMinutes")] = ConfigurationManager.AppSettings["IpLoginFailLimitMinutes"];
                ipBlacklistCfg[IpBlackListKey("LoginSuccessLimit")] = ConfigurationManager.AppSettings["IpLoginSuccessLimitCount"];
                ipBlacklistCfg[IpBlackListKey("LoginFailLimit")] = ConfigurationManager.AppSettings["IpLoginFailLimitCount"];
                ipBlacklistCfg[IpBlackListKey("WhitelistAllMatch")] = ConfigurationManager.AppSettings["IpWhitelistAllMatch"];
                ipBlacklistCfg[IpBlackListKey("WhitelistStoreDb")] = ConfigurationManager.AppSettings["IpWhitelistStoreDb"];
                ipBlacklistCfg[IpBlackListKey("Whitelist")] = ConfigurationManager.AppSettings["IpWhitelist"];
                ipBlacklistCfg[IpBlackListKey("Tips")] = ConfigurationManager.AppSettings["IpRequestLimitTips"];
                ipBlacklistCfg[IpBlackListKey("TokenAuthCheckIp")] = ConfigurationManager.AppSettings["TokenAuthCheckIp"];
                ipBlacklistCfg[DeviceBlackListKey("DeviceBlackListLockTimeOut")] = "01:00:00";
                ipBlacklistCfg[DeviceBlackListKey("DeviceLoginFailLimit")] = "20";
                ipBlacklistCfg[DeviceBlackListKey("DeviceLoginFailTime")] = "-1";
                ipBlacklistCfg[DeviceBlackListKey("DeviceLoginSuccessLimit")] = "60";
                ipBlacklistCfg[DeviceBlackListKey("DeviceLoginSuccessTime")] = "-1";
                ipBlacklistCfg[IpBlackListKey("SellerLoginSuccessLimit")] = "5";
                ipBlacklistCfg[IpBlackListKey("SellerLoginFailLimit")] = "5";
                ipBlacklistCfg[IpBlackListKey("SellerLoginSuccessLimitMinutes")] = "-1440";
                ipBlacklistCfg[IpBlackListKey("SellerLoginFailLimitMinutes")] = "-1440";
                ipBlacklistCfg[IpBlackListKey("SellerIpLockExpired")] = "00:30:00";
                //买手IP黑名单拒绝登录  2016-08-24
                ipBlacklistCfg[IpBlackListKey("SellerDenyLogin")] = "lan";
                return ipBlacklistCfg;
            }

            public static string IpBlackListKey(string key)
            {
                return string.Format("{0}_{1}_{2}", "BlackList", "Ip", key);
            }

            public static string DeviceBlackListKey(string key)
            {
                return string.Format("{0}_{1}_{2}", "BlackList", "Device", key);
            }

            private static string LoginSafeKey(string key)
            {
                return string.Format("{0}_{1}_{2}", "AppBlacklist", "AppBlacklist", key);
            }
        }        
    }
}
